package com.fulihui.wgj.consumer.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fulihui.open.weixin.enums.MsgTypeEnum;
import com.fulihui.wgj.consumer.entity.WxUserInfoExp;
import com.fulihui.wgj.consumer.service.UserService;
import com.fulihui.wgj.consumer.service.Wx48HUserService;
import com.fulihui.wgj.facade.msg.EventMsg;
import com.fulihui.wgj.facade.request.wx48.Wx48AttentionSaveRequest;
import com.fulihui.wgj.facade.service.wx48.Wx48NewsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.testng.collections.Lists;

import java.util.List;

/**
 * @author: LiuJie
 * @version: 2018/7/20 17:34
 * @description:
 */
@Component
@Slf4j
public class Wx48HUserServiceImpl implements Wx48HUserService{

    /**
     * 符合客服消息触发的事件/消息类型
     * 1、用户发送信息
     * 2、点击自定义菜单（仅有点击推事件、扫码推事件、扫码推事件且弹出“消息接收中”提示框这3种菜单类型是会触发客服接口的）
     * 3、关注公众号
     * 4、扫描二维码
     * 5、支付成功
     * 6、用户维权
     */
    private List<String> accordMsgType = Lists.newArrayList("text",
            "subscribe","SCAN","CLICK","scancode_push","scancode_waitmsg");

    @Autowired
    private UserService userService;
    @Reference(version = "1.0.0")
    private Wx48NewsInfoService wx48NewsInfoService;
    @Override
    public void upsert48HUser(EventMsg eventMsg) {
        if(!isAccordWith(eventMsg)){
            return;
        }
        String appId = eventMsg.getAppId();
        String openid = eventMsg.getFromUserName();
        WxUserInfoExp userInfo = userService.getUserInfo(appId, openid);
        if(null == userInfo){
            log.error("48H 互动用户入库-用户信息拉取失败！");
            return;
        }
        Wx48AttentionSaveRequest request = new Wx48AttentionSaveRequest();
        request.setAppId(appId);
        request.setOpenid(openid);
        request.setSex(userInfo.getSex().intValue());
        request.setCity(userInfo.getCity());
        request.setCountry(userInfo.getCountry());
        request.setProvince(userInfo.getProvince());
        request.setMsgType(eventMsg.getMsgType());
        request.setEventType(eventMsg.getEvent());

        wx48NewsInfoService.saveAttention(request);

    }

    /**
     * 消息类型是否满足客服消息推送条件
     * @param eventMsg
     * @return
     */
    private boolean isAccordWith(EventMsg eventMsg){

        if(accordMsgType.contains(eventMsg.getEvent())
                || accordMsgType.contains(eventMsg.getMsgType())){
            return true;
        }

        return false;
    }


}
